﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace CivilRegistry.Logger
{
    /// <summary>
    /// Static Logger to log the errors.
    /// </summary>
    public static class ErrorLogger
    {
        /// <summary>
        /// Logs the errors on database.
        /// </summary>
        /// <param name="ex">Exception</param>
        /// <returns>Returns True if log succeeded.</returns>
        public static bool Log(Exception ex)
        {
            using (CivilDB objCivilDB = new CivilDB(ConfigurationManager.ConnectionStrings["CivilRegistryDB"].ToString()))
            {
                try
                {
                    List<SqlParameter> parameters = new List<SqlParameter>();
                    string[] exDetails = null;

                    SqlParameter parameter = new SqlParameter("@IsApplicationError", SqlDbType.Bit);
                    parameter.Value = true;
                    parameters.Add(parameter);

                    parameter = new SqlParameter("@Page", DbType.String);
                    int requiredIndex = ex.StackTrace.IndexOf(@"CivilRegistry\");
                    exDetails = ex.StackTrace.Substring(requiredIndex, ex.StackTrace.Length - requiredIndex).Split(' '); //Replace(".aspx.cs:line ", "");
                    parameter.Value = exDetails[0].Replace(":line","");
                    parameters.Add(parameter);

                    parameter = new SqlParameter("@LineNumber", DbType.Int32);
                    parameter.Value = exDetails[1].Replace("\r\n","");
                    parameters.Add(parameter);

                    parameter = new SqlParameter("@StackTrace", DbType.String);
                    parameter.Value = ex.StackTrace;
                    parameters.Add(parameter);

                    parameter = new SqlParameter("@ErrorMessage", DbType.String);
                    parameter.Value = ex.Message;
                    if (ex.InnerException != null)
                    {
                        parameter.Value += Environment.NewLine + "Inner Exception: " + Environment.NewLine;
                        parameter.Value += ex.InnerException.Message;
                    }
                    parameters.Add(parameter);

                    parameter = new SqlParameter("@ErrorDate", DbType.DateTime);
                    parameter.Value = DateTime.Now;
                    parameters.Add(parameter);

                    objCivilDB.ExecuteNonQuery("uspInsertErrorDetails", parameters);

                    return true;
                }
                catch
                {
                    // Ignore the error.
                    return false;
                }
            }
        }
    }
}
